package top.dreamlove.core.Single;

import top.dreamlove.constant.Constant;
import top.dreamlove.utils.HttpUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Download {
    //下载进度监控
    private DownloadInfoRunnable runnable;

    public void download(String url) throws IOException {

        if(url == null) return;
        //设置文件下载路径
        String filePath =  Constant.Path + HttpUtils.getHttpFileName(url);
        //连接对象
        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url);
        // 获取文件大小并赋值
        runnable = new DownloadInfoRunnable(httpURLConnection.getContentLength());
        //创建执行器?
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);


        try(
                InputStream is = httpURLConnection.getInputStream();
                BufferedInputStream bs = new BufferedInputStream(is);
                FileOutputStream fs = new FileOutputStream(filePath);
                BufferedOutputStream bo = new BufferedOutputStream(fs);

        ){
            scheduledExecutorService.scheduleAtFixedRate(runnable,0,1, TimeUnit.SECONDS);//循环查询进度
            int b;//读入的数据长度
            byte[] readBuffer = new byte[1024 * 8];//暂存读入的数据(缓存满才写入文件)
            while (( b = bs.read(readBuffer) ) != -1){
                runnable.downloadedSize +=( b / Constant.MB );//记录下载文件的大小
                bo.write(readBuffer,0,b);
            }
        }catch (Exception e){
            System.out.println(e);
        }finally {
            //关闭连接
            if(httpURLConnection != null)  httpURLConnection.disconnect();
            //关闭执行器?
            scheduledExecutorService.shutdownNow();
        }

    }
}
